import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';

class AnalyticsService {
  static final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
  static final FirebaseCrashlytics _crashlytics = FirebaseCrashlytics.instance;

  // 获取Analytics实例
  static FirebaseAnalytics get analytics => _analytics;

  // 获取Crashlytics实例
  static FirebaseCrashlytics get crashlytics => _crashlytics;

  // 记录自定义事件
  static Future<void> logEvent({
    required String name,
    Map<String, Object>? parameters,
  }) async {
    try {
      await _analytics.logEvent(
        name: name,
        parameters: parameters,
      );
    } catch (e) {
      print('Analytics logEvent error: $e');
    }
  }

  // 记录上一次屏幕浏览的时间和名称，用于防止短时间内重复记录相同屏幕
  static DateTime? _lastScreenViewTime;
  static String? _lastScreenName;
  static const Duration _minScreenViewInterval = Duration(milliseconds: 500);
  
  // 记录屏幕浏览
  static Future<void> logScreenView({
    required String screenName,
    String? screenClass,
  }) async {
    // 检查是否是短时间内的重复屏幕浏览
    final now = DateTime.now();
    if (_lastScreenViewTime != null && _lastScreenName == screenName) {
      final timeDiff = now.difference(_lastScreenViewTime!);
      if (timeDiff < _minScreenViewInterval) {
        print('忽略短时间内重复的屏幕浏览事件: $screenName');
        return;
      }
    }
    
    // 更新最后一次屏幕浏览记录
    _lastScreenViewTime = now;
    _lastScreenName = screenName;
    
    try {
      await _analytics.logScreenView(
        screenName: screenName,
        screenClass: screenClass,
      );
    } catch (e) {
      print('Analytics logScreenView error: $e');
      // 记录到Crashlytics但不标记为致命错误
      await recordError(e, StackTrace.current, reason: 'logScreenView error', fatal: false);
    }
  }

  // 设置用户属性
  static Future<void> setUserProperty({
    required String name,
    required String? value,
  }) async {
    try {
      await _analytics.setUserProperty(
        name: name,
        value: value,
      );
    } catch (e) {
      print('Analytics setUserProperty error: $e');
    }
  }

  // 设置用户ID
  static Future<void> setUserId(String? userId) async {
    try {
      await _analytics.setUserId(id: userId);
      await _crashlytics.setUserIdentifier(userId ?? '');
    } catch (e) {
      print('Analytics setUserId error: $e');
    }
  }

  // 记录登录事件
  static Future<void> logLogin(String loginMethod) async {
    await logEvent(
      name: 'login',
      parameters: {
        'method': loginMethod,
      },
    );
  }

  // 记录注册事件
  static Future<void> logSignUp(String signUpMethod) async {
    await logEvent(
      name: 'sign_up',
      parameters: {
        'method': signUpMethod,
      },
    );
  }

  // 记录购买事件
  static Future<void> logPurchase({
    required String currency,
    required double value,
    String? transactionId,
    String? itemName,
  }) async {
    await logEvent(
      name: 'purchase',
      parameters: {
        'currency': currency,
        'value': value,
        if (transactionId != null) 'transaction_id': transactionId,
        if (itemName != null) 'item_name': itemName,
      },
    );
  }

  // 记录自定义错误到Crashlytics
  static Future<void> recordError(
    dynamic exception,
    StackTrace? stackTrace, {
    String? reason,
    bool fatal = false,
  }) async {
    try {
      await _crashlytics.recordError(
        exception,
        stackTrace,
        reason: reason,
        fatal: fatal,
      );
    } catch (e) {
      print('Crashlytics recordError error: $e');
    }
  }

  // 记录自定义日志到Crashlytics
  static Future<void> log(String message) async {
    try {
      await _crashlytics.log(message);
    } catch (e) {
      print('Crashlytics log error: $e');
    }
  }

  // 设置自定义键值对到Crashlytics
  static Future<void> setCustomKey(String key, Object value) async {
    try {
      await _crashlytics.setCustomKey(key, value);
    } catch (e) {
      print('Crashlytics setCustomKey error: $e');
    }
  }
}